#!/usr/bin/env bash
SCRIPT_BASE_DIR=$( dirname "${BASH_SOURCE[0]}" )
source "${SCRIPT_BASE_DIR}/common/fs_utils.sh"

set -e

function usage() {
  echo "Usage:$( basename $0 ) [-m <model> | -c <mix_cfg> | -s <start> | -t <step> | -h]"
  echo -e "\t混合量化，percentage从\<start\>开始，每次增加一个步长，直到\>=1为止"
  echo -e "\t-p <dir_prefix> : 量化时--save-dir/-s的路径的前缀,量化模型实际存放路径应该时<dir_prefix>_<per>/, default tmp/quant-model"
  echo -e "\t-m <model> : onnx模型路径"
  echo -e "\t-c <mix_cfg> : 混合量化配置文件"
  echo -e "\t-s <start> : 命令行-per的开始值, default 0.99"
  echo -e "\t-e <end> : 命令行-per的结束值, default 1.0"
  echo -e "\t-t <step> : 每次量化-per值增加一个步长, default 0.001"
  echo -e "\t-i <iteration> : 量化-i/--iteration参数值，default 1"
  echo -e "\t-h 输出此信息"
  exit 1
}

per=0.8
end=1.0
step=0.001
dirPrefix='tmp/quant-model'
iteration=1
while getopts "p:m:c:s:e:t:i:h" arg
do
  case $arg in
    p)
      dirPrefix=$OPTARG
      ;;
    m)
      floatModel=$OPTARG
      ;;
    c)
      mixCfg=$OPTARG
      ;;
    s)
      per=$OPTARG
      ;;
    e)
      end=$OPTARG
      ;;
    t)
      step=$OPTARG
      ;;
    i)
      iteratioin=$OPTARG
      ;; 
    *)
      usage
      ;;
  esac
done

if [ -z "${floatModel}" -o -z "${mixCfg}" ]
then
  echo "-m <model> and -c <mix_cfg>是必需的"
  exit 1
fi

file_exists_or_die "${floatModel}"
file_exists_or_die "${mixCfg}"

# 计算要执行命令的次数，bash循环测试命令只能用整数
cnt=$( echo "(${end} - ${per}) / ${step}" | bc )
# echo ${cnt}
# exit 0

# floatModel='models/mobilenet_v3_small_rne.onnx'
# mixCfg='tmp/mix_config_per.json'
# per='0.8'
# step='0.001'
idx=0
while [ ${idx} -le ${cnt} ]
do
  saveDir="${dirPrefix}_${per}"
  # 量化
  echo ./run_quantization.py -m ${floatModel} -if infer_imagenet_benchmark -i ${iteratioin} --chip TX511 -r quant -mc ${mixCfg}  -s ${saveDir} -per ${per}
  ./run_quantization.py -m ${floatModel} -if infer_imagenet_benchmark -i ${iteratioin} --chip TX511 -r quant -mc ${mixCfg}  -s ${saveDir} -per ${per}
  # compare数据
  echo ./run_quantization.py -m ${floatModel} -if infer_imagenet_benchmark -i ${iteratioin} --chip TX511 -r compare -s ${saveDir}
  ./run_quantization.py -m ${floatModel} -if infer_imagenet_benchmark -i ${iteratioin} --chip TX511 -r compare -s ${saveDir}
  # 增加per值
  per=$( echo ${per} + ${step} | bc )  
  idx=$(( ${idx} + 1 ))
done
